package com.bdqn.business.access.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bdqn.business.access.dao.RoleRepository;
import com.bdqn.business.access.dao.TeacherMapper;
import com.bdqn.business.access.dao.TeacherRepository;
import com.bdqn.business.access.dao.UserRepository;
import com.bdqn.base.BaseService;
import com.bdqn.entity.access.Role;
import com.bdqn.entity.access.Teacher;
import com.bdqn.entity.access.User;
import com.bdqn.entity.access.UserTeacher;
import com.bdqn.error.CommonException;
import com.bdqn.response.Result;
import com.bdqn.response.ResultCode;
import com.bdqn.utils.BeanMapUtils;
import com.bdqn.utils.IdWorker;
import com.bdqn.utils.PinYinUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.lang.reflect.Array;
import java.util.*;

@Service
@Transactional
public class UserService extends BaseService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private TeacherRepository teacherRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TeacherMapper teacherMapper;

    public Result save(User user,Teacher teacher) {
        String id = idWorker.nextId();
        user.setId(id);
        String username = PinYinUtil.toPinyin(user.getNickName()) + (int)(Math.random()*8999);
        user.setUsername(username);
        user.setLevel("user");

        user.setStatus("1");
        user.setPassword(new Md5Hash("123456",username,3).toString()); //参数一: 加密谁?   混淆字符串1234 : 加盐  3 加密次数

        //处理用户与角色的关联关系
        Set<Role> roles = new HashSet<>();
        for (String roleId : user.getRoleIds().split(",")) {
            Role role = roleRepository.findById(roleId).get();
            roles.add(role);
        }

        if(roles != null && roles.size() > 0){
            user.setRoles(roles);

            user.setModifyId(currentUser().getId());
            user.setModifyUser(currentUser().getNickName());
            user.setModifyTime(new Date());

            userRepository.save(user);
            teacher.setId(id);
            teacherRepository.save(teacher);


            return Result.SUCCESS();
        }else{
            return Result.FAIL();
        }
    }

    public Result update(User user,Teacher teacher) {
        User target = userRepository.findById(user.getId()).get();
        BeanUtils.copyProperties(user,target);


        Teacher teacherTarget = teacherRepository.findById(user.getId()).get();

        BeanUtils.copyProperties(teacher,teacherTarget);


        Set<Role> roles = new HashSet<>();
        for (String roleId : user.getRoleIds().split(",")) {
            Role role = roleRepository.findById(roleId).get();
            roles.add(role);
        }

        if(roles != null && roles.size() > 0){
            target.setRoles(roles);

            target.setModifyId(currentUser().getId());
            target.setModifyUser(currentUser().getNickName());
            target.setModifyTime(new Date());

            userRepository.save(target);
            teacherRepository.save(teacherTarget);
            return Result.SUCCESS();
        }else {
            return Result.FAIL();
        }

    }


    public User findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    public Result list(Map<String, Object> map) {
        Object departmentIds = map.get("departmentIds");

        if(departmentIds == null || "".equals(departmentIds)){
            //查询所有教师
            List<Teacher> teachers = teacherRepository.findAll();
            List<Map<String, Object>> maps = this.handleData(teachers);
            return new Result(ResultCode.SUCCESS,maps);
        }else{
            List<Map<String, Object>> list = new ArrayList<>();
            String[] departmentIdArray = departmentIds.toString().split(",");
            for (String departmentId : departmentIdArray) {
                List<Teacher> teacherList = teacherRepository.findByDepartmentId(departmentId);
                List<Map<String, Object>> maps = this.handleData(teacherList);
                for (Map<String, Object> objectMap : maps) {
                    list.add(objectMap);
                }
            }
            return new Result(ResultCode.SUCCESS,list);
        }

    }

    private List<Map<String,Object>> handleData(List<Teacher> teacherList){
        List<Map<String,Object>> list = new ArrayList<>();
        if(teacherList != null && teacherList.size() > 0){
            for (Teacher teacher : teacherList) {
                Map<String, Object> teacherMap = BeanMapUtils.beanToMap(teacher);
                User user = userRepository.findById(teacher.getId()).get();
                Map<String, Object> userMap = BeanMapUtils.beanToMap(user);
                Map<String,Object> objectMap = new HashMap<>();
                objectMap.putAll(teacherMap);
                objectMap.putAll(userMap);


                List<Role> roles = roleRepository.getRoleListByUserId(user.getId());
                //处理用户的角色数据(集合列表显示的)
                List<String> roleNames = new ArrayList<>();
                //处理用户的角色数据(个体回显数据)
                List<String> roleIds = new ArrayList<>();

                if(roles != null && roles.size() > 0){
                    for (Role role : roles) {
                        roleNames.add(role.getName());
                        roleIds.add(role.getId());
                    }
                }


                objectMap.put("roles",roleNames);
                objectMap.put("roleIds", StringUtils.join(roleIds,","));

                list.add(objectMap);
            }
        }
        return list;
    }

    public Result findTeachersByJobTitle() throws CommonException {
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("job_title","教员")
                .or()
                    .eq("job_title","班主任")
                .or()
                    .eq("job_title","助教");

        queryWrapper.orderByDesc("job_title");

        List<Teacher> teachers = teacherMapper.selectList(queryWrapper);

        Map<String,List<UserTeacher>> map = new HashMap<>();

        List<UserTeacher> zjTeacher = new ArrayList<>();
        List<UserTeacher> jyTeacher = new ArrayList<>();
        List<UserTeacher> bzrTeacher = new ArrayList<>();

        if(teachers != null && teachers.size() > 0){
            for (Teacher teacher : teachers) {

                User user = userRepository.findById(teacher.getId()).get();

                UserTeacher userTeacher = new UserTeacher();
                BeanUtils.copyProperties(teacher,userTeacher);
                BeanUtils.copyProperties(user,userTeacher);

                switch (teacher.getJobTitle()){
                    case "助教":
                        zjTeacher.add(userTeacher);
                        break;
                    case "教员":
                        jyTeacher.add(userTeacher);
                        break;
                    case "班主任":
                        bzrTeacher.add(userTeacher);
                        break;
                    default:
                        throw new CommonException(ResultCode.FAIL);
                }
            }
        }

        map.put("zjTeacher",zjTeacher);
        map.put("jyTeacher",jyTeacher);
        map.put("bzrTeacher",bzrTeacher);

        return new Result(ResultCode.SUCCESS,map);
    }
}
